# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
# SPDX-License-Identifier: MIT

import os
import logging
from pathlib import Path
from typing import Optional
from common_base import setup_logger 

logger = setup_logger()

def save_markdown_file(content: str, file_path: str) -> bool:
    """Save content as Markdown file.
    
    Args:
        content: The markdown content to save
        file_path: Path where to save the file
        
    Returns:
        bool: True if successful, False otherwise
    """
    # try:
    # 确保目录存在
    Path(file_path).parent.mkdir(parents=True, exist_ok=True)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    logger.info(f"Markdown report saved to: {file_path}")
    return True
    # except Exception as e:
    #     logger.error(f"Failed to save markdown file: {e}")
    #     return False

def save_pdf_file(content: str, file_path: str) -> bool:
    """Convert markdown content to PDF and save.
    
    Args:
        content: The markdown content to convert
        file_path: Path where to save the PDF file
        
    Returns:
        bool: True if successful, False otherwise
    """
    try:
        import markdown
        from weasyprint import HTML, CSS
        from io import StringIO
        
        # 确保目录存在
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        
        # 转换 Markdown 到 HTML
        html_content = markdown.markdown(
            content, 
            extensions=['tables', 'fenced_code', 'toc']
        )
        
        # 添加基本的 CSS 样式
        css_style = """
        body { 
            font-family: Arial, sans-serif; 
            line-height: 1.6; 
            margin: 40px;
            color: #333;
        }
        h1, h2, h3 { 
            color: #2c3e50; 
            margin-top: 30px;
        }
        table { 
            border-collapse: collapse; 
            width: 100%; 
            margin: 20px 0;
        }
        th, td { 
            border: 1px solid #ddd; 
            padding: 12px; 
            text-align: left; 
        }
        th { 
            background-color: #f2f2f2; 
            font-weight: bold;
        }
        code { 
            background-color: #f4f4f4; 
            padding: 2px 4px; 
            border-radius: 3px;
        }
        pre { 
            background-color: #f4f4f4; 
            padding: 15px; 
            border-radius: 5px; 
            overflow-x: auto;
        }
        """
        
        # 创建完整的 HTML 文档
        full_html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <style>{css_style}</style>
        </head>
        <body>
            {html_content}
        </body>
        </html>
        """
        
        # 转换为 PDF
        HTML(string=full_html).write_pdf(file_path)
        
        logger.info(f"PDF report saved to: {file_path}")
        return True
    except ImportError as e:
        logger.error(f"Missing dependencies for PDF generation: {e}")
        logger.error("Please install: pip install markdown weasyprint")
        return False
    except Exception as e:
        logger.error(f"Failed to save PDF file: {e}")
        return False
